package com.xiyue.server.exception;


import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.sport.common.web.model.Result;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

/**
 *  全局异常处理
 *
 */
@Hidden
@Slf4j
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler(value = NotLoginException.class)
    public Result<String> handle(NotLoginException e, HttpServletRequest request) {
        // 如果没传递token时，应返回未传递登录凭证
        String tokenName = request.getHeader(StpUtil.getTokenName());
        if(StrUtil.isBlank(tokenName)) {
            return Result.error(401,"登陆凭证未传递",request.getRequestURI());
        }
        log.error("Sa-Token鉴权异常———————— url:{}", request.getRequestURI());

        return Result.error(401,e.getMessage(),request.getRequestURI());
    }

    @ExceptionHandler(value = NotPermissionException.class)
    public Result<String> handle(NotPermissionException e, HttpServletRequest request) {
        log.error("Sa-Token鉴权异常———————— url:{}", request.getRequestURI());
        return Result.error(403,e.getMessage(),request.getRequestURI());
    }

    @ExceptionHandler(value = NotRoleException.class)
    public Result<String> handle(NotRoleException e, HttpServletRequest request) {
        log.error("Sa-Token鉴权异常———————— url:{}", request.getRequestURI());
        return Result.error(403,e.getMessage(),request.getRequestURI());
    }

//    @ExceptionHandler(value = SQLException.class)
//    public Result<String> handle(SQLException e, HttpServletRequest request) {
//        log.error("sql语句异常———————— url:{}", request.getRequestURI());
//        return Result.error(500,e.getMessage(),request.getRequestURI());
//    }
}
